package com.bwie.es.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bwie.common.domain.request.DocInfoReq;
import com.bwie.common.result.Result;
import com.bwie.es.service.EsDocService;
import com.bwie.es.service.EsIndexService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

@Service
@Slf4j
public class EsDocServiceImpl implements EsDocService {

    public EsIndexService esIndexService;

    @Resource
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private HttpServletRequest request;

    @Override
    public Result createDoc(DocInfoReq docInfoReq) {

        //打印请求参数
        log.info("请求参数:{}", JSONObject.toJSONString(docInfoReq));
        try {
            //校验索引是否存在
            if (!indexExists(docInfoReq.getIndexName())) {
                return Result.error("索引不存在,无法创建");
            }
            //如果不存在则抛出异常
            //如果存在则创建文栏
            //校验datas是否为空
            if (docInfoReq.getDatas() == null || docInfoReq.getDatas().isEmpty()) {
                return Result.error("文档数据为空,无法创建");
            }
            //批量请求对象
            BulkRequest bulkRequest = new BulkRequest();
            for (Map<String, Object> data : docInfoReq.getDatas()) {
                IndexRequest indexRequest = new IndexRequest(docInfoReq.getIndexName());
                if (docInfoReq.isNeeId()) {
                    String id = data.get(docInfoReq.getIdField()).toString();
                    indexRequest.id(id);
                }
                indexRequest.source(data, XContentType.JSON);
                bulkRequest.add(indexRequest);
            }

            BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
            if (bulkResponse.hasFailures()) {
                //失败
                return Result.error("部分文档创建失败:"+bulkResponse.buildFailureMessage());
            }else {
                return Result.success("文档创建成功");
            }
        } catch (IOException e) {
            throw new RuntimeException("文档创建失败"+e.getMessage());
        }

        //遍历datas
        //获取docInfoReq中的isneedId
        //如果为true
        //获取docInfoReq中的idField
        //获取根据idField的值，去datas中的map中取出id
        //构建索引请求IndexRequest
        //设置索引名称
        //设置文档1d
        //设置文档内容
        //调用RestHighLevelClient的index方法执行创建文档
        //对index方法做try catch处理
        //迭代为批量插入
    }

    private boolean indexExists(String indexName) {
        GetIndexRequest request = new GetIndexRequest(indexName);
        try {
            return restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException("索引不存在");
        }
    }


}
